#include "tlm.h"

int tlm_start(){
  return udp_start(CLIENT_PORT);
}

int external_start(){
  return udp_start(EXT_CMD_PORT);
}

int udp_start(int port){
    int sock;
    struct sockaddr_in addr;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sock != -1);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(CLIENT_IP);

    assert(fcntl(sock, F_SETFL, O_NONBLOCK, 1) != -1);
    int sock_buf_size = 256;
    assert(setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &sock_buf_size, sizeof(int)) != -1);

    assert(bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != -1);

    return sock;
}

int recv_external_cmd(int sock, char* payload){
  return recv(sock, payload, sizeof(char), 0);
}

void send_tlm(int sock, gcs_tlm_t* tlm){
  send(sock, tlm, sizeof(gcs_tlm_t), 0);
}

int recv_tlm(int sock, gcs_tlm_t* tlm){
  return recv(sock, tlm, sizeof(gcs_tlm_t), 0);
}
